package com.example.sunmiv1.room

import android.util.Log
import com.example.sunmiv1.room.entity.OrderEntity
import com.example.sunmiv1.utils.GsonTools
import com.google.gson.Gson
import io.realm.Realm
import java.util.UUID


object OrderManager {
    private val TAG=javaClass.simpleName
    suspend fun add(entity: OrderEntity){
        Log.e(TAG, "add: entity=${Gson().toJson(entity)}", )
        // 获的realm
        val realm = Realm.getDefaultInstance();

        realm.beginTransaction()

//在这里里面插入或者更新
        val user = realm.createObject(OrderEntity::class.java,System.currentTimeMillis());//插入数据
        user.init(entity.orderNo,entity.remake)
        realm.commitTransaction();
        realm.close()
    }
    suspend fun getAll():List<OrderEntity>{
        // 获的realm
        val realm = Realm.getDefaultInstance();

        realm.beginTransaction();
        val result = realm.where(OrderEntity::class.java)
            .findAll();
        Log.e(TAG, "getAll: size=${result.size}", )
        val json=result.asJSON()
        Log.e(TAG, "getAll: json=$json", )
        val list=GsonTools.getObjectList(json,OrderEntity::class.java)
        Log.e(TAG, "getAll: size=${list.size} list=${GsonTools.beanToJson(list)}", )
        realm.commitTransaction();
        realm.close()
        return list
    }
    suspend fun findOrderNo(orderNo:String):List<OrderEntity>{
        Log.e(TAG, "findUserId: orderNo=$orderNo", )
        // 获的realm
        val realm = Realm.getDefaultInstance();
        realm.beginTransaction();
        val result = realm.where(OrderEntity::class.java)
            .equalTo("orderNo",orderNo)
            .findAll();
        Log.e(TAG, "findUserId: size=${result.size}", )
        val json=result.asJSON()
        Log.e(TAG, "findUserId: json=$json", )
        val list=GsonTools.getObjectList(json,OrderEntity::class.java)
        Log.e(TAG, "findUserId: size=${list.size} list=${GsonTools.beanToJson(list)}", )
        realm.commitTransaction();
        realm.close()
        return list
    }
    suspend fun update(entity: OrderEntity):List<OrderEntity>{
        Log.e(TAG, "update: entity=${GsonTools.beanToJson(entity)}", )
        // 获的realm
        val realm = Realm.getDefaultInstance();
        realm.beginTransaction();
        val result = realm.where(OrderEntity::class.java)
            .equalTo("orderNo",entity.orderNo)
            .findAll();
        Log.e(TAG, "update: size=${result.size}", )
        val json=result.asJSON()
        Log.e(TAG, "update: json=$json", )
        val list=GsonTools.getObjectList(json,OrderEntity::class.java)
        Log.e(TAG, "findUserId: size=${list.size} list=${GsonTools.beanToJson(list)}", )
        result.setString("orderNo",entity.orderNo)
        result.setString("remake",entity.remake)
        realm.commitTransaction();
        realm.close()
        return list
    }
}

